package com.chually.cloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: zuul网关过滤器
 * @project: spring-cloud-demo-parent
 * @author: yupei 2018/8/10 10:11
 */
@Component
public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        /**
        pre：可以在请求被路由之前调用
        route：在路由请求时候被调用
        post：在route和error过滤器之后被调用
        error：处理请求时发生错误时被调用
         */
        return "pre";
    }

    @Override
    public int filterOrder() {
        /** 优先级为0，数字越大，优先级越低 */
        return 0;
    }

    @Override
    public boolean shouldFilter() {
       /** 是否执行该过滤器，此处为true，说明需要过滤*/
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        System.out.println(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            System.out.println("token is empty, please input accessToken");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty, please input accessToken");
            }catch (Exception e){}

            return null;
        }
        System.out.println("ok");
        return null;
    }
}
